package com.utils.search;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.bappi.utils.HttpUtils;
import com.bappi.utils.Utils;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

public class SearchUtils {

	private static final int MAX_RESULT = 10;
	private static final String KEY = "AIzaSyCmoIs6VLibe1KH0EmiuXIAtwPR1zBW6YQ";

	private static final String PLACE_URL_FORMAT = "https://maps.googleapis.com/maps/api/place/search/json?key=%s&location=%f,%f&radius=%d&sensor=false&name=%s&types=%s";

	public static final void search(final String name, final Context context,
			final OnSearchCompleteListener oscl,
			final boolean showProgressDialog, final double lat,
			final double lon, final int rad, final String types) {
		new AsyncTask<String, String, String>() {
			private ProgressDialog progressDialog;
			private List<SearchResult> results;

			protected void onPreExecute() {
				if (showProgressDialog) {
					progressDialog = Utils.getProgressDialog(context);
					progressDialog.show();
				}
			};

			protected String doInBackground(String... arg0) {
				try {
					results = new ArrayList<SearchResult>();
					// final String url = String.format(PLACE_URL_FORMAT, KEY,
					// lat, lon,
					// rad, types);
					final String url = String.format(PLACE_URL_FORMAT, KEY,
							lat, lon, rad, name, types);
					String curUrl;
					String nextToken = null;
					while (results.size() < MAX_RESULT) {
						curUrl = (nextToken == null) ? url : url
								+ "&pagetoken=" + nextToken;
						Log.i("DREG", "curUrl=" + curUrl);
						String resp = HttpUtils.getHttpResponseAsString(curUrl);
						// Log.i("DREG", resp);
						JSONObject jo = new JSONObject(resp);
						JSONArray ja = jo.getJSONArray("results");
						nextToken = jo.optString("next_page_token");
						// Log.i("DREG", "nextToken="+nextToken);
						JSONObject res;
						JSONObject loc;
						SearchResult result;
						for (int i = 0; (i < ja.length())
								&& (results.size() < MAX_RESULT); i++) {
							try {
								res = ja.getJSONObject(i);
								String nm = res.optString("name");
								Log.i("DREG", "NAME=" + nm);

								result = new SearchResult();
								loc = res.getJSONObject("geometry")
										.getJSONObject("location");
								result.id = loc.optLong("id");
								result.lat = loc.optDouble("lat");
								result.lng = loc.optDouble("lng");
								result.icon = res.optString("icon");
								result.name = nm;
								result.reference = res.optString("reference");
								result.vicinity = res.optString("vicinity");
								result.types = res.optJSONArray("types");
								result.rating = res.optDouble("rating");
								results.add(result);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
						if ((nextToken == null) || (nextToken.length() == 0)
								|| (results.size() >= MAX_RESULT)) {
							break;
						} else {
							Thread.sleep(1100);
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}

			protected void onPostExecute(String unused) {
				try {
					if (showProgressDialog) {
						progressDialog.dismiss();
					}
					oscl.onResult(results);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.execute();
	}

}
